package com.example.mycarcalling.fragment;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.lib_cache.adapter.UserAdapter;
import com.example.lib_cache.dao.OnUserNickNameClickListener;
import com.example.lib_cache.model.Order;
import com.example.lib_cache.model.User;
import com.example.lib_cache.service.ApiService;
import com.example.lib_cache.viewmodel.MapFragmentViewModel;
import com.example.lib_cache.viewmodel.UserFragmentViewModel;
import com.example.lib_cache.viewmodel.WaitingActivityViewModel;
import com.example.lib_common.base.BaseFragment;

import com.example.lib_common.util.SpUtils;
import com.example.mycarcalling.R;
import com.example.mycarcalling.activity.EditActivity;
import com.example.mycarcalling.activity.NavSettlementDialog;
import com.example.mycarcalling.activity.OrderNavActivity;
import com.example.mycarcalling.activity.PasswordEditActivity;
import com.example.mycarcalling.activity.PickUpActivity;
import com.example.mycarcalling.activity.TravelActivity;
import com.example.mycarcalling.activity.WaitingActivity;
import com.example.mycarcalling.databinding.FragmentUserBinding;
import com.google.android.material.navigation.NavigationView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;


/**
 * 用户模块
 */

@AndroidEntryPoint
public class UserFragment extends BaseFragment {

    public static final String TAG = UserFragment.class.getSimpleName();
    private final static int REQUEST_WAITING = 2;
    private final static int REQUEST_PICKUP = 3;
    private final static int REQUEST_TRAVEL = 4;

    private static final int REQUEST_USERINFO = 0;
    private static final int REQUEST_PHONE = 11;
    private static final int REQUEST_PASSWORD = 12;
    private static final int REQUEST_ORDER = 13;
    private static final int REQUEST_LOGOUT = 14;


    @Inject
    ApiService apiService;

    private FragmentUserBinding fragmentUserBinding;
    private UserFragmentViewModel userFragmentViewModel;
    private LinearLayoutManager llm = null;
    private UserAdapter userAdapter = null;
    private Intent intent = null;

    private NavSettlementDialog navSettlementDialog = null;

    private Context context = null;


    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_user;
    }

    @Override
    protected void initView() {

        fragmentUserBinding = DataBindingUtil.bind(view.getRootView());
        fragmentUserBinding.setLifecycleOwner(this);
        navSettlementDialog = new NavSettlementDialog(view.getContext());
        iniData();
        initListener();
        initObserve();

        //判断token是否存在进入用户主页

    }

    private void iniData() {
        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getActivity().getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        userFragmentViewModel= viewModelProvider.
                get(UserFragmentViewModel.class);


        llm = new LinearLayoutManager(view.getContext());
        fragmentUserBinding.rcHeadUser.setLayoutManager(llm);
        Log.d(TAG,"开始通过token获取用户信息");
        userFragmentViewModel.loadingUserData(apiService,view.getContext());
        userAdapter = new UserAdapter(view.getContext());
        fragmentUserBinding.rcHeadUser.setAdapter(userAdapter);

    }

    private void initObserve(){

        userFragmentViewModel.getUserMutableLiveData().observe(this, new Observer<User>() {

            @Override
            public void onChanged(User user) {
                Log.d(TAG,"User发生变化"+ user.getNickname());
                userAdapter.updateData(user);
                userAdapter.notifyDataSetChanged();

            }
        });

        //得到订单状态
        userFragmentViewModel.getOrderMutableLiveData().observe(this, new Observer<Order>() {
            @Override
            public void onChanged(Order order) {
                if(order.getOrderStatus()==1){
                    Intent intent = new Intent(view.getContext(),PickUpActivity.class);
                    startActivityForResult(intent,REQUEST_PICKUP);
                }
                if(order.getOrderStatus()==2){
                    Intent intent = new Intent(view.getContext(),TravelActivity.class);
                    startActivityForResult(intent,REQUEST_TRAVEL);
                }
            }
        });

        //结算数据转换完成
        userFragmentViewModel.getIsTransform().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    navSettlementDialog.getTvDistance().setText(
                            userFragmentViewModel.getDistance());
                    navSettlementDialog.getTvDistanceUnit().setText(
                            userFragmentViewModel.getDistanceUnit());
                    navSettlementDialog.getTvDuration().setText(
                            userFragmentViewModel.getDuration());
                    navSettlementDialog.show();

                }
            }
        });
    }

    private void initListener(){

        fragmentUserBinding.nvUserItem.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                Log.d(TAG, String.valueOf(item.getItemId()));
                switch (item.getItemId()){

                    case R.id.it_phone:
                        Log.d(TAG,"用户手机号码点击");
                        intent = new Intent(view.getContext(),EditActivity.class);
                        userFragmentViewModel.saveData();
                        intent.putExtra("request","phone");
                        startActivityForResult(intent,REQUEST_PHONE);
                        break;

                    case R.id.it_password_update:
                        Log.d(TAG,"用户密码修改点击");
                        intent = new Intent(view.getContext(), PasswordEditActivity.class);
                        view.getContext().startActivity(intent);
                        break;
                    case R.id.it_order:
                        Log.d(TAG,"用户历史订单点击");

                        intent = new Intent(view.getContext(), OrderNavActivity.class);
                        startActivityForResult(intent,REQUEST_ORDER);

                        break;
                    case R.id.it_logout:
                        Log.d(TAG,"用户注销登录点击");
                        userFragmentViewModel.logout();
                        userFragmentViewModel.loadingUserData(apiService,view.getContext());
                        break;
                }

                return true;
            }
        });

        userAdapter.setOnUserNickNameClickListener(new OnUserNickNameClickListener() {
            @Override
            public void startEdit() {
                Log.d(TAG,"触发更新用户昵称");
                Intent intent = new Intent(view.getContext(), EditActivity.class);
                intent.putExtra("request","nickName");
                userFragmentViewModel.saveData();
                startActivityForResult(intent,REQUEST_USERINFO);

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if(resultCode==1){
//            userFragmentViewModel.loadingUserData(apiService,view.getContext());
//        }
        if(requestCode == REQUEST_USERINFO) {
            if (resultCode == 1) {
                userFragmentViewModel.loadingUserData(apiService,view.getContext());
            }
        }
        if(requestCode == REQUEST_ORDER){
            if(resultCode == 10){
                Intent intent = new Intent(view.getContext(),WaitingActivity.class);
                startActivityForResult(intent,REQUEST_WAITING);
            }
            if(resultCode == 11){
                //获取订单信息
                userFragmentViewModel.requestOrderStatus(apiService,view.getContext());
            }
        }
        if(requestCode == REQUEST_WAITING){
            if(resultCode == 1){
                Intent intent = new Intent(view.getContext(),PickUpActivity.class);
                startActivityForResult(intent,REQUEST_PICKUP);
            }
        }

        if(requestCode == REQUEST_PICKUP){
            if(resultCode == 1){
                //开启目的地导航
                Intent intent = new Intent(view.getContext(), TravelActivity.class);
                startActivityForResult(intent,REQUEST_TRAVEL);
            }
        }
        if(requestCode == REQUEST_TRAVEL){
            if(resultCode == 1){
                Log.d(TAG,"旅程结束");
                //结算
                DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(System.currentTimeMillis());
                String thisTime = simpleDateFormat.format(date);
                String lastTime = SpUtils.getString(view.getContext(),"lastTime");

                userFragmentViewModel.transformTime(lastTime,thisTime);
            }
        }
    }
}
